/*
 * Copyright (C) 2011 Jake Wharton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.timothy.fund.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sina.stock.data.SinaStockClient;
import com.sina.stock.data.SinaStockInfo;
import com.sina.stock.data.SinaStockInfo.ParseStockInfoException;
import com.timothy.fund.adapter.StockAAdaptor;
import com.timothy.fund.bean.StockA;
import com.timothy.fund.data.AnalyzeData;

public class StockAListActivity extends SherlockActivity {
	public static final String LOG_TAG = "StockAListActivity";
	
	public static int THEME = R.style.Theme_Sherlock;
	Context mContext;
	ListView stockAlistView;
//	List<StockA> displayList = new ArrayList<StockA>();
	List<StockA> saList;
	StockAAdaptor adaptor ;

	private SinaStockClient mClient;
    private String message;

    private void initClient() {
    	mClient = SinaStockClient.getInstance();
    }
    
	public void getData(){
		String[] stockABases = getResources().getStringArray(R.array.stock_a_bases);
		
		//得到StockA代码列表
		String[] quotes = AnalyzeData.parseStockAQuotes(stockABases);
		
		Map<String,SinaStockInfo> saMap; //quote&info Map
		Map<String,Double> svMap; //quote&value Map
		try {
			//获取证券代码和信息（key:代码 Value 信息）
			saMap = mClient.getStockInfoMap(quotes);
			
			////得到StockA代码，价格列表
			svMap = AnalyzeData.getStockAValues(stockABases);
			
			//获取StockA列表信息
			saList = AnalyzeData.getStockAPriceList(saMap,svMap);
//			displayList.addAll(saList);
		} catch (HttpException e) {
			Log.e(LOG_TAG,e.getMessage());
		} catch (IOException e) {
			Log.e(LOG_TAG,e.getMessage());
		} catch (ParseStockInfoException e) {
			Log.e(LOG_TAG,e.getMessage());
		}
	}
	
	public void displayData(){
	       //set List
        adaptor = new StockAAdaptor(mContext,saList); 
        stockAlistView = (ListView)findViewById(R.id.stocka_listview);
        stockAlistView.setAdapter(adaptor);
        stockAlistView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
//				Intent intent = new Intent();
//				intent.setClass( mContext, StockAListActivity.class);
//				startActivity(intent);
			}      	
        });		
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar
        menu.add("Refresh")
            .setIcon(R.drawable.ic_refresh)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //This uses the imported MenuItem from ActionBarSherlock
//        Toast.makeText(this, "Data refreshed!", Toast.LENGTH_SHORT).show();
        reLoadData();
        return true;
    }
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(StockAListActivity.THEME); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stock_a);
        
        mContext = getApplicationContext();
        
        initClient();
        reLoadData();
    }
    
    public void reLoadData(){
    	new Thread(getDataRunnable).start();
    }
    
    private Runnable getDataRunnable = new Runnable(){
        @Override
        public void run() {
            try {
            	getData();
                message = "success";
            } catch (Exception e) {
            	Log.e(LOG_TAG,e.getMessage());
            	message = "fail";
			}
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
            
    };
    
    //set picture
    private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            myDialog.dismiss();
//            imageView.setImageBitmap(bitmap);
            Toast.makeText(StockAListActivity.this, message, Toast.LENGTH_SHORT).show();
            if("success".equalsIgnoreCase(message)){
            	displayData();
            }
        }
    };
 
}
